﻿#include "GradientButton.h"
#include <QPainter>
#include <QtMath> // 包含M_PI
GradientButton::GradientButton(QWidget *parent):QPushButton(parent),GradientColor(false)
{
    m_Timer = new QTimer(this);

//    setStyleSheet("QPushButton {"
//                  "border: 3px solid transparent;"
//                  "border-radius: 5px;"
//              "}");

    connect(m_Timer, &QTimer::timeout, this, &GradientButton::updateStyle);
    m_Timer->setInterval(30);
}

void GradientButton::startAnimation(bool isStart)
{
    if(isStart)
    {
        GradientColor = true;
        m_Timer->start(20);
    }
    else
    {
        GradientColor = false;
        m_Timer->stop();
        update();
    }
}

void GradientButton::paintEvent(QPaintEvent *event)
{
    QPushButton::paintEvent(event);

    if(GradientColor)
    {
        QPainter painter(this);
        painter.setRenderHint(QPainter::Antialiasing);

        /*
    // 绘制渐变边框
    QLinearGradient gradient(0, 0, width(), height());  // 从左上到右下
    gradient.setColorAt(0, Qt::red);  // 左上角
    gradient.setColorAt(1, Qt::blue); // 右下角

    QPen pen(gradient, 3);  // 3像素宽的渐变笔刷
    painter.setPen(pen);
    painter.drawRoundedRect(rect(), 5, 5);  // 绘制圆角矩形边框
    */

        // 计算渐变的起点和终点
        int width = this->width();
        int height = this->height();
        QPoint start = QPoint(width / 2, height / 2);
        QPoint end = start + QPoint(cos(angle) * width, sin(angle) * height);

        // 创建线性渐变
        QLinearGradient gradient(start, end);
        gradient.setColorAt(0, Qt::darkGreen); // 左上角
        gradient.setColorAt(1, Qt::green); // 右下角

        // 设置笔刷和绘制边框
        QPen pen(gradient, 2); // 2像素宽的渐变笔刷
        painter.setPen(pen);
        painter.drawRoundedRect(this->rect(), 2, 2); // 绘制圆角矩形边框
    }

}

void GradientButton::updateStyle()
{
    /*
    angle += 0.1; // 更新角度，可以根据需要调整
    if (angle >= 2 * M_PI)
        angle = 0;
    */

    double angleIncrement = 0.1 * (1 - 0.5 * (std::abs(std::sin(angle)) + std::abs(std::cos(angle))));
    angle += angleIncrement;
    if (angle >= 2 * M_PI)
        angle = 0;

    update();
}

// 计算旋转角度的函数
double GradientButton::calculateRotationAngle(double x, double y, int milliseconds)
{
    // 确保输入的毫秒数在0到1000之间
    if (milliseconds < 0 || milliseconds > 1000) {
        return 0.0;
    }

    // 计算矩形的周长
    double perimeter = 2 * (x + y);

    // 计算P点在矩形边上的移动距离
    double distance = (milliseconds / 1000.0) * perimeter;

    // 计算P点在矩形边上的位置
    double position = fmod(distance, perimeter);

    // 计算旋转角度
    double angle = 0.0;

    if (position < x) {
        // P点在AB边上
        angle = 90.0 * (position / x);
    } else if (position < x + y) {
        // P点在BC边上
        angle = 90.0 + 90.0 * ((position - x) / y);
    } else if (position < 2 * x + y) {
        // P点在CD边上
        angle = 180.0 + 90.0 * ((position - x - y) / x);
    } else {
        // P点在DA边上
        angle = 270.0 + 90.0 * ((position - 2 * x - y) / y);
    }

    return angle;
}
